﻿using Prism.Mvvm;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MengLin.Studying.PrismApp.ViewModel.First
{
    //第一种情况：处理数据、值验证（ErrorsContainer）
    //第二种情况：处理命令
    public class FirstWindowVM: BindableBase, INotifyDataErrorInfo
    {
        /// <summary>
        /// Ctor
        /// </summary>
        public FirstWindowVM()
        {
            MyProperty = "123456";
        }

        private string _myProperty;
        public string MyProperty
        {
            get { return _myProperty; }
            set
            {
                //_myVar = value;

                //第一种方式
                //this.RaisePropertyChanged();
                //通知其他属性
                //this.RaisePropertyChanged("其他属性名称");

                // 第二种方式
                //this.SetProperty(ref myVar, value, "MyProperty");
                this.SetProperty<string>(ref _myProperty, value, () =>
                {
                    //onChanged
                });

                //基于ErrorsContainer的数据校验方式
                if (value == "1234")
                {
                    // 异常消息
                    ErrorsContainer.SetErrors("MyProperty", new string[] { "输入值无效1234" });
                }
                else
                {
                    ErrorsContainer.ClearErrors("MyProperty");
                }
            }
        }

        //OnPropertyChanged;
        //CanExecuteChanged;
        private ErrorsContainer<string> _errorsContainer;
        public ErrorsContainer<string> ErrorsContainer
        {
            get
            {
                if (_errorsContainer == null)
                {
                    _errorsContainer = new ErrorsContainer<string>((propName) =>
                    {
                        // 异常信息的处理
                        ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propName));
                    });
                }
                return _errorsContainer;
            }
            set { _errorsContainer = value; }
        }

        /// <summary>
        /// INotifyDataErrorInfo接口方法
        /// </summary>
        public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
        public bool HasErrors
        {
            get
            {
                return ErrorsContainer.HasErrors;
            }
        }

        public IEnumerable GetErrors(string propertyName)
        {
            return ErrorsContainer.GetErrors(propertyName);
        }
    }
}
